/**
 * Created by yuanlian on 2016/8/8.
 */
function RegisterController($scope, Register,$state,$timeout,store,User,API,$http) {
    var vm = this;
    var updateClock=function(){
        if(vm.getCheckSec==0){
            clearInterval(vm.timer1)
            return
        }
        vm.getCheckSec--;
    }
    //获取验证码
    vm.getSecurityCode = function () {
        if (!vm.form.mobile.$valid) {
            vm.mobileInvalid = true
            vm.securityCodeMsg = '请输入正确格式的手机号'

            return
        }
        vm.mobileInvalid = false

        Register.getSecurityCode({phone: vm.user.mobile}).$promise.then(function (response) {

            vm.getCheckSec = 300
            vm.timer1=setInterval(function () {
                $scope.$apply(updateClock());
            }, 1000);
        }).catch(function(error){

            vm.mobileInvalid = true
            vm.securityCodeMsg =error.message
        })



    }

    //注册
    vm.register=function(user){
        vm.registerSending=true
        var params={
            securityCode:user.securityCode,
            mobilePhone:user.mobile,
            mail:user.email,
            password:user.password
        }
        Register.register(params).$promise.then(function(response){
            vm.session={
                password:user.password,
                username:user.mobile
            }
            $http.post(API + '/weblogin', vm.session)

                // 根据 ID 查询登录用户信息
                .then(function(response) {
                    response.data.imageDiyBgVo = JSON.parse(response.data.imageDiyBgVo)
                    store.set('loginInfo', response.data)
                    return User.getSelf().$promise
                })

                // 记住当前用户并跳转
                .then(function(user) {
                    store.set('currentAdmin', user)
                    var expireDate = new Date();
                    expireDate.setDate(expireDate.getDate() + 3);
                    store.set('expireDate', expireDate)
                    $state.go('web.list')
                })

                // 捕获错误
                .catch(function(rejection) {
                    vm.flash = rejection
                    $timeout(function() { delete vm.flash }, 3000)
                })

        })
            .catch(function(error){
                vm.flash = error
                $timeout(function() { delete vm.flash }, 3000)
            })
    }

    vm.cancel=function(){
        $state.go('session.signin')
    }

    //验证重复密码是否相同
    $scope.$watch('vm.user', function (newValue, oldValue) {
        if (newValue) {
            if (newValue.passwordReply) {
                if (!_.isEqual(newValue.passwordReply, newValue.password)) {
                    vm.pwdInvalid = true
                    vm.form.passwordReply.$invalid = true

                } else {
                    vm.pwdInvalid = false
                    vm.form.passwordReply.$invalid = false
                }
            }


        }
    }, true)
}